package com.wyt.common.tool;

import java.time.Duration;
import java.time.LocalDateTime;

/**
 * @ClassName RunTimeRecordUtil
 * @Description: 运行时长记录工具类
 * @Author wangyongtao
 * @Date 2021/8/3 15:46
 * @Version 1.0
 **/
public class RunTimeRecordUtil {
    /** 线程局部变量，存储每个线程处理的开始时间 */
    private static ThreadLocal<LocalDateTime> startDates = new ThreadLocal<>();

    /**
     * @Description 设置当前线程处理的开始时间
     * @author wangyongtao
     */
    public static void initStartTime(){
        startDates.set(LocalDateTime.now());
    }

    /**
     * @Description 获取执行时长，单位 秒
     * @author wangyongtao
     */
    public static long getDiff(){
        //1、计算时长
        LocalDateTime startDate = startDates.get();
        LocalDateTime stopDate = LocalDateTime.now();
        Duration duration = Duration.between(startDate,stopDate);
        //2、释放资源，防止threadlocal内存泄漏
        startDates.remove();
        //3、返回
        return duration.toMillis()/1000;
    }

}
